/*
 * @lc app=leetcode.cn id=19 lang=cpp
 *
 * [19] 删除链表的倒数第 N 个结点
 */
#include "include.h"

struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head) {return head;}

        int listLength = 1;
        ListNode* nodePtr = head;
        while (nodePtr->next){
            listLength += 1;
            nodePtr = nodePtr->next;
        }
        // printf("%d\n", listLength);

        int wantedNodeIndex = listLength - n;
        int currentIndex = 0;
        nodePtr = head;
        ListNode* preNodePtr = head;
        while (currentIndex != wantedNodeIndex){
            preNodePtr = nodePtr;
            nodePtr = nodePtr->next;
            currentIndex += 1;
        }

        if (nodePtr == head){
            ListNode* res = nodePtr->next;
            delete nodePtr;
            return res;
        } else{
            preNodePtr->next = nodePtr->next;
            delete nodePtr;
            return head;
        }
    }
};
// @lc code=end

